package com.hank.handler;

import com.alibaba.fastjson2.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gaoZhiHao
 * @date 2023/4/28 16:41
 */
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private List<WebSocketSession> sessions = new ArrayList<>();
    private List<String> dataList = new ArrayList<>();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接收到客户端发送的信息时触发
        String payload = message.getPayload();
        System.out.println("接收到消息：" + payload);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 与客户端完成连接时触发
        super.afterConnectionEstablished(session);

        // 将新建立的 WebSocket 会话添加到 sessions 集合中
        sessions.add(session);

        // 发送数据列表给客户端
        TextMessage message = new TextMessage(JSON.toJSONString(dataList));
        session.sendMessage(message);
    }

    /**
     * 新增数据并广播给所有客户端
     * @param data 新增数据
     */
    public void addData(String data) {
        dataList.add(data);
        broadcast();
    }

    /**
     * 广播数据列表给所有客户端
     */
    private void broadcast() {
        TextMessage message = new TextMessage(JSON.toJSONString(dataList));
        for (WebSocketSession session : sessions) {
            try {
                session.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}